//
//  TurnOutViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/12.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "TurnOutViewController.h"
#import "TurnOutView.h"
#import "SetPayPasswordViewController.h"

#define ButtonNumber    2
@interface TurnOutViewController ()<UIScrollViewDelegate,HTTPClientDelegate,TurnOutViewDelegate,SetPayPasswordViewControllerDelegate>
{
    UIButton *_bankTransferredButton;
    UIButton *_amountTransferredButton;
    UIView   *_buttonView;
    UIView   *_buttonLineView;
    
    TurnOutView *bankView;
    TurnOutView *accountView;
    
    double _sqbBalance;
    double _sqbFreezeBalance;
}
@property (weak, nonatomic) IBOutlet UIView *cutView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) BOOL          isLoading;
@end

@implementation TurnOutViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavBarTitle:@"转出" andLeftItemName:@"返回" andRightItemName:@""];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self initData];
    [self initView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addBankCardSuccess) name:@"addBankCardSuccess" object:nil];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addBankCardSuccess {
    [self requestData];
}

#pragma mark - Delegate
- (void)turnOutSuccess {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sqbBalanceChange" object:nil];
    
    [self back];
}

- (void)gotoSetTradePassword {
    //设置交易密码
    SetPayPasswordViewController *setPayPassword = [[SetPayPasswordViewController alloc] init];
    setPayPassword.delegate = self;
    setPayPassword.editType = 1;
    [self.navigationController pushViewController:setPayPassword animated:YES];
}

- (void)setPayPasswordSuccess {
    [bankView reloadTradePwdStaus];
    [accountView reloadTradePwdStaus];
}

#pragma mark - Action
- (void)headerButtonClick:(UIButton *)button {
    if (button == _bankTransferredButton) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = _buttonLineView.frame;
            frame.origin.x = 0;
            _buttonLineView.frame = frame;
            _scrollView.contentOffset = CGPointMake(0, 0);
        } completion:^(BOOL finished) {
            [self buttonChange:button];
        }];
    }else if(button == _amountTransferredButton){
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = _buttonLineView.frame;
            frame.origin.x = MSWIDTH/ButtonNumber;
            _buttonLineView.frame = frame;
            _scrollView.contentOffset = CGPointMake(MSWIDTH, 0);
        } completion:^(BOOL finished) {
            [self buttonChange:button];
        }];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        double OriginX = scrollView.contentOffset.x;
        if (OriginX>=0 && OriginX<=MSWIDTH) {
            CGRect frame = _buttonLineView.frame;
            frame.origin.x = (OriginX/MSWIDTH)*(MSWIDTH/ButtonNumber);
            _buttonLineView.frame = frame;
            
            if (OriginX <= MSWIDTH/2) {
                [self buttonChange:_bankTransferredButton];
            }else {
                [self buttonChange:_amountTransferredButton];
            }
        }
    }
}

- (void)buttonChange:(UIButton *)button {
    if (button == _bankTransferredButton) {
        [_bankTransferredButton setTitleColor:KColor forState:UIControlStateNormal];
        _bankTransferredButton.titleLabel.font = KFontBoldSize(14.0);
        
        [_amountTransferredButton setTitleColor:KBlackColor forState:UIControlStateNormal];
        _amountTransferredButton.titleLabel.font = KFontSize(14.0);
        
    }else if (button == _amountTransferredButton) {
        [_bankTransferredButton setTitleColor:KBlackColor forState:UIControlStateNormal];
        _bankTransferredButton.titleLabel.font = KFontSize(14.0);
        
        [_amountTransferredButton setTitleColor:KColor forState:UIControlStateNormal];
        _amountTransferredButton.titleLabel.font = KFontBoldSize(14.0);
    }
}

#pragma mark - Data
- (void)initData {
    
    [self requestData];
}

- (void)requestData {
    _requestType = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"503" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"--%@",dics);
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            NSString *balance = [NSString stringWithFormat:@"%@",[CommonClass formatConversion:[dics[@"balance"] doubleValue] type:1]];
            accountView.balanceStr = balance;
            
            _sqbFreezeBalance = [dics[@"freeze"] doubleValue];
            accountView.sqbFreezeBalance = _sqbFreezeBalance;
            bankView.sqbFreezeBalance = _sqbFreezeBalance;
            
            _sqbBalance = [dics[@"balance3"] doubleValue];
            accountView.sqbBalance = _sqbBalance;
            bankView.sqbBalance = _sqbBalance;
            
            
            NSArray *userBanks = dics[@"userBanks"];
            if (userBanks.count > 0) {
                NSDictionary *bankDict = userBanks[0];
                bankView.userBanksDict = bankDict;
            }else {
                bankView.userBanksDict = nil;
            }
        }
        
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    
}

- (void) networkError {
    
}

#pragma mark - View
- (void)initView {
    [self loadButtonView];
    
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(MSWIDTH*2, 0);
    _scrollView.pagingEnabled = YES;
    
    NSArray *bankNib = [[NSBundle mainBundle] loadNibNamed:@"TurnOutView" owner:self options:nil];
    bankView = [bankNib objectAtIndex:0];
    bankView.viewType = 1;
    bankView.delegate = self;
    bankView.frame = RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 64 - KAdaptNum(45));
    [bankView loadView];
    [_scrollView addSubview:bankView];
    
    NSArray *accountNib = [[NSBundle mainBundle] loadNibNamed:@"TurnOutView" owner:self options:nil];
    accountView = [accountNib objectAtIndex:0];
    accountView.viewType = 2;
    accountView.delegate = self;
    accountView.frame = RECTMAKE(MSWIDTH, 0, MSWIDTH, MSHIGHT - 64 - KAdaptNum(45));
    [accountView loadView];
    [_scrollView addSubview:accountView];
    
    
}

- (void)loadButtonView {
    
    CGFloat scrollOriginY = KAdaptNum(45);
    
    _buttonView = [UIView viewWithFrame:CGRectMake(0, 0, MSWIDTH, scrollOriginY) backgroundColor:[UIColor whiteColor] superview:self.view];
    
    _bankTransferredButton = [UIButton buttonWithFrame:CGRectMake(0, 0, MSWIDTH/ButtonNumber, scrollOriginY - 1) backgroundColor:nil title:@"转出到银行卡" titleColor:KColor titleFont:14.0 target:self action:@selector(headerButtonClick:) superview:_buttonView];
    
    _amountTransferredButton = [UIButton buttonWithFrame:CGRectMake(MSWIDTH/ButtonNumber, 0, MSWIDTH/ButtonNumber, GetHeight(_bankTransferredButton)) backgroundColor:nil title:@"转出到余额" titleColor:KBlackColor titleFont:14.0 target:self action:@selector(headerButtonClick:) superview:_buttonView];
    
    
    UIView *buttonLine = [UIView viewWithFrame:CGRectMake(0, CGRectGetMaxY(_bankTransferredButton.frame), MSWIDTH, _buttonView.frame.size.height - CGRectGetMaxY(_bankTransferredButton.frame)) backgroundColor:KlayerBorder superview:_buttonView];
    
    _buttonLineView = [UIView viewWithFrame:CGRectMake(0, 0, MSWIDTH/ButtonNumber, buttonLine.frame.size.height) backgroundColor:KColor superview:buttonLine];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
